import type { PropType } from 'vue'
import { defineComponent, ref, computed } from 'vue'
import { Option } from '../../_util/normalizeOptions'
import Tag from '../../tag'

export default defineComponent({
  name: 'Selector',
  props: {
    prefixCls: String,
    values: Array as PropType<Option[]>,
    searchValue: String,
    multiple: Boolean,
    showArrow: Boolean,
    filterable: Boolean,
    clearable: Boolean,
    disabled: Boolean,
    placeholder: String,
    inputRef: { default: () => ref<HTMLInputElement>() },
    onSelect: Function,
    onSearch: Function,
    onToggleOpen: Function,
    onFocus: Function as PropType<(e: FocusEvent) => void>,
    onBlur: Function as PropType<(e: FocusEvent) => void>
  },
  setup(props) {
    function onSelect(item) {
      props.onSelect?.(item)
    }
    function onClick() {
      props.inputRef.value.focus()
    }
    function onMousedown() {
      props.onToggleOpen()
    }
    function onInputChange(e: Event) {
      props.onToggleOpen(true)
      props.onSearch((e.target as HTMLInputElement).value)
    }

    return () => {
      const { prefixCls, values, multiple } = props
      const inputProps = {
        ref: props.inputRef,
        class: `${prefixCls}_search_input`,
        value: props.searchValue,
        disabled: props.disabled || (!props.filterable && !props.multiple),
        placeholder: !values.length ? props.placeholder : undefined,
        onInput: onInputChange,
        onFocus: props.onFocus,
        onBlur: props.onBlur
      }

      // prettier-ignore
      const tagsNode = multiple ? values.map(e => <Tag class={`${prefixCls}_tag`} closable={!props.disabled} onClose={() => onSelect(e)}>{e?.label}</Tag>) : undefined;
      const textNode = <span class={`${prefixCls}_text`}>{!multiple && !props.searchValue ? values[0]?.label : ' '}</span>

      return (
        <div class={`${prefixCls}_selector`} onClick={onClick} onMousedown={onMousedown}>
          {tagsNode}
          <div class={`${prefixCls}_search`}>
            <input {...inputProps} />
          </div>
          {textNode}
        </div>
      )
    }
  }
})
